<template>
  <div class="employees-container">
    <div class="app-container">
      <PageTools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button v-allow="'import_employee'" type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button v-allow="'export——employee'" type="danger" size="small" @click="hExport">excel导出</el-button>
          <el-button v-allow="'tianjia'" type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </PageTools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="list">
          <el-table-column label="序号" type="index" :index="indexMethod" />
          <el-table-column label="工号" sortable prop="workNumber" />
          <el-table-column label="头像">
            <template slot-scope="scope">
              <image-holder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template slot-scope="scope">
              {{ formatEmployment(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry" />
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id='+scope.row.id)">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(scope.row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            :current-page.sync="curPage"
            :pager-count="5"
            :page-size="2"
            :page-sizes="[2, 5, 10]"
            @size-change="handleSizeChange"
            @current-change="hCurrentChange"
          />
        </el-row>
      </el-card>
    </div>
    <!-- 新增员工弹层 -->
    <el-dialog
      title="新增员工"
      :visible.sync="showDialog"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      @close="hCloseDialog"
    >
      <addor-edit
        ref="addorEdit"
        @close="showDialog=false"
        @update-empolyee="hUpdateEmpolyee"
      />
    </el-dialog>

    <!-- 分配角色弹窗 -->
    <el-dialog
      title="分配员工"
      :visible.sync="showRoleDialog"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      @close="hClose"
    >
      <AssignRole
        ref="assignRole"
        :cur-id="curId"
        @close="showRoleDialog=false"
        @update-close="hUpdateClose"
      />
    </el-dialog>
  </div>
</template>
<script>

import PageTools from '@/components/PageTools'
import { getEmployeeList, delEmployee } from '@/api/employees'
import types from '@/constant/employees'
import addorEdit from './empDialog.vue'
import AssignRole from './assignRole.vue'
const hireType = types.hireType
const hireTypEnmu = hireType.reduce((acc, item) => { return { ...acc, [item.id]: item.value } }, {})
console.log('hireType', hireTypEnmu)
export default {
  namne: 'Employees',
  components: {
    PageTools,
    // eslint-disable-next-line vue/no-unused-components
    'addor-edit': addorEdit,
    AssignRole
  },
  data() {
    return {
      list: [],
      total: 0,
      page: 1,
      pageSize: 2,
      showDialog: false,
      curPage: 1,
      showRoleDialog: false,
      curId: ''
    }
  },
  computed: {
    indexMethod() {
      return (this.page - 1) * this.pageSize + 1
    }

  },
  created() {
    this.loadEmployeeList()
  },
  methods: {

    // 删除
    async hDel(id) {
      try {
        const res = await delEmployee(id)
        this.$message.success('删除成功')
        if (this.list.length === 1) {
          this.page--
          if (this.page.length <= 0) {
            this.page = 1
          }
        }
        // 重新渲染
        this.loadEmployeeList()
        console.log(res)
      } catch (err) {
        this.$message.error(err.message)
      }
    },
    // 切换分页数据条数
    handleSizeChange(val) {
      // 选中显示条数赋值给pageSize
      this.pageSize = val
      // 重新渲染
      this.loadEmployeeList()
    },
    async loadEmployeeList() {
      try {
        const res = await getEmployeeList(this.page, this.pageSize)
        console.log(res)
        this.list = res.data.rows
        this.total = res.data.total
        this.curPage = this.page // 通知分页组件去更新页码数据
      } catch (err) {
        console.log(err)
      }
    },
    formatEmployment(num) {
      return hireTypEnmu[num]
    },
    hCurrentChange(curPage) {
      this.page = curPage
      this.loadEmployeeList()
    },
    hCloseDialog() {
      this.$refs.addorEdit.resetForm()
      console.log('子组件信息', this.$refs.addorEdit)
    },
    hUpdateEmpolyee() {
      this.showDialog = false
      if (this.total % this.pageSize === 0) {
        this.page = (this.total / this.pageSize) + 1
      } else {
        // 最后一页的页码
        this.page = Math.floor(this.total / this.pageSize) + 1
      }
      this.loadEmployeeList()
    },
    // 导出
    formatData(list) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      console.log(list)
      let data = []
      let header = []
      const one = list[0]
      if (!one) {
        return { header, data }
      }
      header = Object.keys(one).map(key => {
        return map[key]
      })

      data = list.map(obj => {
        const key = obj['formOfEmployment']
        // console.log(key)
        obj['formOfEmployment'] = hireTypEnmu[key]
        console.log(obj['formOfEmployment'] = hireTypEnmu[key], '--------')

        return Object.values(obj)
      })
      console.log(data)
      return { header, data }
    },
    hExport() {
      import('@/vendor/Export2Excel').then(async excel => {
        const res = await getEmployeeList(this.page, this.size)
        const list = res.data.rows
        console.log('从后端获取的数据', list)

        const { header, data } = this.formatData(list)
        console.log('聘用方式', data)
        // excel表示导入的模块对象
        excel.export_json_to_excel({
          header: header, // 表头 必填
          data: data,
          // 具体数据 必填
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    hClose() {
    },
    // 分配角色
    hAssignRole(id) {
      this.showRoleDialog = true
      console.log(id)
      this.curId = id
      // 操作子组件调用事件
      this.$nextTick(() => {
        this.$refs.assignRole.loadRoles()
      })
    },
    hUpdateClose() {
      this.showRoleDialog = false
      this.loadEmployeeList()
    }

  }
}
</script>
